<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>
        <el-form
          ref="form"
          label-width="120px"
          :model="form"
          :rules="rules"
          size="small"
        >
          <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="form.subjectID" @change="getCatalog">
              <el-option
                v-for="item in subjects"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="form.catalogID">
              <el-option
                v-for="item in catalogList"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="form.enterpriseID">
              <el-option
                v-for="item in enterpriseList"
                :key="item.value"
                :label="item.company"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <el-select
              v-model="form.province"
              class="double"
              @change="selectCity"
            >
              <el-option
                v-for="item in provinces"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>

            <el-select v-model="form.city" class="double">
              <el-option
                v-for="item in citys"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="方向：" prop="direction">
            <el-select v-model="form.direction">
              <el-option
                v-for="item in direction"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              v-model="form.questionType"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              v-model="form.difficulty"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-form-item>

          <el-form-item label="题干：" prop="question" style="height: 250px">
            <quill-editor
              ref="myQuestionEditor"
              v-model="form.question"
              :options="editorOption"
              style="height: 200px"
            />
          </el-form-item>
          <!-- 根据选择的类型来判断是多选还是单选 -->
          <el-form-item label="选项：" class="question-select">
            <div v-if="form.questionType === 1" class="radio">
              <el-radio
                v-for="item in form.options"
                :key="item.code"
                style="display: flex; align-items: center; margin: 15px 0"
                :label="item.isRight"
                :value="true"
                @change.native="changeRadio(item.code)"
              >
                {{ item.code + ':' }}
                <el-input v-model="item.title" type="text" />
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  style="display: flex; align-items: center"
                  :on-change="onchange"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                >
                  <span
                    style="font-size: 14px"
                    @click="currentCode = item.code"
                  >
                    上传图片
                  </span>
                  <i class="el-icon-circle-close" />
                </el-upload>
              </el-radio>
            </div>

            <div v-else-if="form.questionType === 2" class="checkbox">
              <el-checkbox
                v-for="item in form.options"
                :key="item.code"
                :label="item.isRight"
                style="margin: 15px 0"
                :value="item.isRight"
                @change.native="changeCheck(item.code)"
              >
                {{ item.code + ':' }}
                <el-input v-model="item.title" type="text" />
                <el-upload
                  action="#"
                  list-type="picture-card"
                  style="display: inline-block"
                >
                  <span style="font-size: 14px">上传图片</span>
                  <i class="el-icon-circle-close" />
                </el-upload>
              </el-checkbox>
            </div>
            <!-- 选择是3 就啥也不渲染 上面俩是真条件渲染 -->
            <el-button
              type="danger"
              size="small"
              :disabled="form.questionType !== 2 || form.options.length >= 26"
              @click="addOption"
            >
              +增加选项与答案
            </el-button>
          </el-form-item>

          <el-form-item label="解析视频：">
            <el-input v-model="form.videoURL" />
          </el-form-item>

          <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              ref="myAnswerEditor"
              v-model="form.answer"
              :options="editorOption"
              style="height: 200px"
            />
          </el-form-item>

          <el-form-item
            label="题目备注："
            style="width: 520px; margin-top: 70px"
          >
            <el-input type="textarea" :rows="4" />
          </el-form-item>

          <el-form-item label="试题标签：">
            <el-select v-model="form.tags" multiple collapse-tags>
              <el-option
                v-for="item in tags"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="!id" type="primary" @click="addNewQuestion">
              确认提交
            </el-button>
            <el-button v-else type="success" @click="updateQuestion">
              确认修改
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { questionType, difficulty } from '@/api/constants/constants'
import {
  getsimpleApi,
  getdirectorysApi,
  getcompanylistApi,
  gettagsApi
} from '@/api/subjeckts'
import { provinces, citys } from '@/api/constants/city' // 获取城市常量
import { direction } from '@/api/constants/constants' // 获取方向
import {
  getAddQuestionsApi,
  getQuestionxqApi,
  getUpdataQuestionApi
} from '@/api/questions'

import { Message } from 'element-ui'
export default {
  components: { quillEditor },
  props: {},
  data() {
    return {
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '', // 方向
        questionType: '', // 题型 选择是单选还是多选
        difficulty: '', // 选择 题型难度
        question: '', // 问题
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ], // 定义选项
        videoURL: '',
        answer: '', // 答案解析
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        answer: [{ required: true, message: '请输入题干', trigger: 'change' }]
      },
      questionType, // 题型 选择是单选还是多选
      difficulty, // 选择 题型难度
      editorOption: {
        placeholder: '',
        theme: 'snow',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 列表
              ['blockquote', 'code-block', 'image', 'link'] // 代码块 上传图片、上传视频
            ]
          }
        }
      },
      dialogImageUrl: '', // 图片地址
      dialogVisible: false, // 关闭
      subjects: [], // 学科列表
      catalogList: [], // 目录列表
      enterpriseList: [], // 企业列表
      provinces: [], // 省列表
      citys: [], // 城市列表
      direction, // 方向
      answerOptions: [],
      tags: [], // 题目标签
      fileList: [],
      currentCode: '',
      questionDetail: {},
      id: this.$route.query.id // 根据id判断是不是编辑
    }
  },
  watch: {},
  async created() {
    this.provinces = provinces() // 获取省列表
    this.getQuestionMessages() // 进来请求一下要获取的数据
    if (this.id) {
      this.getQuestion()
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.onchange(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 获取学科列表 企业列表
    async getQuestionMessages() {
      const data = await getsimpleApi()
      this.subjects = data
      const res = await getcompanylistApi({ pagesize: 10000 })

      this.enterpriseList = res.items
    },
    selectCity() {
      this.form.city = '' // 情况一下防止上次
      this.citys = citys(this.form.province)
    },
    // 获取目录列表 根据学科id 来获取目录 和 tags
    async getCatalog() {
      const data = await getdirectorysApi(this.form.subjectID)
      this.catalogList = data.items
      const res = await gettagsApi(this.form.subjectID)
      this.tags = res
    },
    async addNewQuestion() {
      try {
        await this.$refs.form.validate()
        const data = this.dealForm(this.form)
        console.log(data)
        await getAddQuestionsApi(data)
        Message.success('添加基础题库成功')
        this.$router.push('/questions/basic')
      } catch (error) {
        console.log(error)
      }
    },
    changeRadio(code) {
      this.form.options = this.form.options.map((item) => {
        item.isRight = false
        if (item.code === code) {
          item.isRight = true
        }
        return item
      })
    },
    changeCheck(code) {
      this.form.options = this.form.options.map((item) => {
        if (item.code === code) {
          item.isRight = !item.isRight
        }
        return item
      })
    },
    addOption() {
      const num =
        this.form.options[this.form.options.length - 1].code.charCodeAt()
      const code = String.fromCharCode(num + 1)
      this.form.options.push({ isRight: false, code, title: '', img: '' })
    },
    onchange(file, filelist) {
      this.fileList = filelist
      const str = this.fileList.map((item) => item.url).join(',')
      this.form.options.forEach((item) => {
        if (item.code === this.currentCode) {
          item.img = str
        }
      })
    },
    // 做数据回显
    async getQuestion() {
      const data = await getQuestionxqApi(this.id)
      this.form = data
      console.log(data)
    },
    // 更新编辑接口
    async updateQuestion() {
      await getUpdataQuestionApi(this.id, this.form)
        .then(() => {
          this.$message.success('更新成功')
          this.$router.push({ path: '/questions/basic' })
        })
        .catch((error) => {
          this.$message.success(error)
        })
    },
    dealForm(form) {
      const data = { ...form }
      data.tags = data.tags.join(',')
      data.difficulty = data.difficulty + ''
      data.questionType = data.questionType + ''
      return data
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  width: 400px;
}
.double {
  ::v-deep .el-input__inner {
    width: 198px;
    margin-right: 4px;
  }
}
::v-deep .el-upload--picture-card {
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
  color: #333333;
  background-color: #fff;
  .el-icon-circle-close {
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(50%, -50%);
    font-size: 18px;
    color: #999;
    background-color: #fff;
  }
}
.question-select {
  ::v-deep .el-radio__label {
    display: flex;
    align-items: center;
    .el-input__inner {
      width: 240px;
      height: 36px;
      margin-right: 5px;
    }
  }
  ::v-deep .el-checkbox {
    display: flex;
    align-items: center;
    .el-checkbox__label {
      display: flex;
      align-items: center;
      .el-input__inner {
        width: 240px;
        height: 36px;
        margin-right: 5px;
      }
    }
    .el-checkbox__inner {
      border-radius: 50%;
    }
  }
}

::v-deep .el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>
